package com.jcl.traffic.security.rest;

import com.jcl.traffic.security.model.Role;
import com.jcl.traffic.security.model.User;
import com.jcl.traffic.security.repository.UserRepository;
import com.jcl.traffic.security.service.AuthService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * @author jcl_hqu
 * @date 2020/11/22 10:57
 */

@RequestMapping("authentication")
@Controller
@RequiredArgsConstructor
@Slf4j
public class JwtAuthController {
    private final UserRepository userRepository;
    private final AuthService authService;

    // 登录
    @RequestMapping(value = "/test")
    public String createToken(HttpServletRequest request, Model model) throws AuthenticationException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String token=authService.login(username, password);
        model.addAttribute("token",token);
        if (token==null) return "redirect:/error.html";
        else return "redirect:/index.html";


    }

    // 注册
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public User register(@RequestBody User addedUser ) throws AuthenticationException {
        return authService.register(addedUser);
    }


    /**
     * Check user`s login info, then create a jwt token returned to front end
     * @param user
     * @return jwt token
     * @throws ServletException
     */
    @PostMapping("login")
    public String login(User user,Model model) throws ServletException {
        // Check if username and password is null
        if (user.getUsername() == "" || user.getUsername() == null
                || user.getPassword() == "" || user.getPassword() == null)
            throw new ServletException("Please fill in username and password");

        // Check if the username is used
        if(userRepository.findByUsername(user.getUsername()) == null
                || !user.getPassword().equals(userRepository.findByUsername(user.getUsername()).getPassword())){
            throw new ServletException("Please fill in username and password");
        }

        // Create Twt token
        String jwtToken = Jwts.builder().setSubject(user.getUsername()).claim("roles", "member").setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, "secretkey").compact();

        model.addAttribute("token",jwtToken);
        if (jwtToken==null) return "redirect:/error";
        else return "redirect:/admin/index";
        //重定向至主页
    }
}
